package com.lgy.message;

import com.alibaba.fastjson.JSONObject;
import com.lgy.product.common.ProductInfoOutput;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ProductInfoReceiver {

    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String message) {
        // message 转 ProductInfoOutput
        List<ProductInfoOutput> productInfoOutputList = JSONObject.parseArray(message, ProductInfoOutput.class);
        // 存储到redis
        productInfoOutputList.forEach(e -> stringRedisTemplate.opsForValue()
                .set(String.format(PRODUCT_STOCK_TEMPLATE, e.getProductId()), String.valueOf(e.getProductStock())));
    }

}
